const fs = require('fs')
const https = require('https')
const http = require('http')
const Config = require("./Config");
const {getSongIdFromUrl} = require("./Helper");


class Download
{

    /**
     * 下载网易云音乐文件
     * @param {string} url - 音频真实地址（从 weapi 响应捕获）
     * @param {string} filePath - 要保存的文件路径
     * @param {string} refer
     * @param {string} cookieValue - 登录后复制的 MUSIC_U Cookie（VIP 用户必填）
     */
    static downloadWithHeaders (url, filePath,refer = 'https://music.163.com/', cookieValue = '')
    {
        return new Promise((resolve, reject) => {
            const options = {
                headers: {
                    'User-Agent': Config.userAgent,
                    'Referer': refer,
                    'Cookie': cookieValue ? `${Config.cookieName}=${cookieValue};` : '',
                },
            };
            const songId = getSongIdFromUrl(refer);
            if (!songId) {
                reject(new Error('❌ 无法从 refer 提取歌曲 ID'));
                return;
            }
            console.log(`🎵 正在下载: ${url}`);

            const filename = filePath+`/${songId}.mp3`;

            const file = fs.createWriteStream(filename);
            const client = url.startsWith('https') ? https : http; // 根据协议选择模块
            client
                .get(url, options, (res) => {
                    if (res.statusCode !== 200) {
                        reject(new Error(`HTTP 状态码: ${res.statusCode}`));
                        return;
                    }

                    res.pipe(file);
                    file.on('finish', () => {
                        file.close();
                        console.log('✅ 下载完成:', filename);
                        resolve();
                    });
                })
                .on('error', (err) => {
                    fs.unlink(filename, () => reject(err));
                });
        });
    }
} //end Download

module.exports = Download